﻿using FrameworkCore.Interfaces;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json.Linq;
using System.Net.Http.Headers;
using System.Text.RegularExpressions;

namespace Infrastructure.Services;

#nullable disable

public class OcrService: IOcrService
{
    private readonly HttpClient _httpClient;
    private readonly IConfiguration _configuration;

    // 构造函数，注入 HttpClient 实例
    public OcrService(HttpClient httpClient, IConfiguration configuration)
    {
        _httpClient = httpClient;
        _configuration = configuration;
    }

    /// <summary>
    /// 图片识别
    /// </summary>
    /// <param name="filePath">文件路径</param>
    /// <returns>返回识别结果</returns>
    public async Task<string> PerformOcrAsync(string filePath)
    {
        using (var form = new MultipartFormDataContent())
        {
            // 读取文件内容
            var fileContent = new ByteArrayContent(File.ReadAllBytes(filePath));

            // 根据文件扩展名确定内容类型
            var contentType = GetContentType(filePath);
            fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse(contentType);

            // 将文件内容添加到表单中
            form.Add(fileContent, "file", Path.GetFileName(filePath));

            var ocrServiceUrl = _configuration["OcrServiceUrl"];

            // 发送 POST 请求到 OCR API
            var response = await _httpClient.PostAsync($"{ocrServiceUrl}/ocr", form);

            // 确保响应成功
            response.EnsureSuccessStatusCode();

            // 读取并返回响应内容
            var content = await response.Content.ReadAsStringAsync();

            JObject jsonObject = JObject.Parse(content);


            if (jsonObject.TryGetValue("text", out JToken value) && value.Type == JTokenType.String)
            {
                string unicodeString = (string)value;
                return unicodeString;
            }

            return string.Empty;
        }
    }

    // 根据文件扩展名返回对应的内容类型
    private string GetContentType(string filePath)
    {
        var extension = Path.GetExtension(filePath).ToLowerInvariant();
        return extension switch
        {
            ".png" => "image/png",
            ".jpg" => "image/jpeg",
            ".jpeg" => "image/jpeg",
            ".pdf" => "application/pdf",
            _ => "application/octet-stream" // 默认内容类型
        };
    }

    /// <summary>
    /// 将包含 Unicode 转义字符的字符串转换为实际字符。
    /// </summary>
    /// <param name="unicodeString">包含 Unicode 转义字符的字符串。</param>
    /// <returns>转换后的实际字符字符串。</returns>
    private static string ConvertUnicodeString(string unicodeString)
    {
        // 正则表达式匹配 Unicode 转义字符
        var regex = new Regex(@"\\u([0-9A-Fa-f]{4})");
        var matches = regex.Matches(unicodeString);

        // 替换每个 Unicode 转义字符
        string result = unicodeString;
        foreach (Match match in matches)
        {
            string hex = match.Groups[1].Value;
            int codePoint = Convert.ToInt32(hex, 16);
            char character = (char)codePoint;

            // 替换字符串中的 Unicode 转义字符
            result = result.Replace(match.Value, character.ToString());
        }

        //// 处理 \\n 转义字符
        var newlineRegex = new Regex(@"\\n");
        result = newlineRegex.Replace(result, "\n");

        return result;
    }
}
